package com.tsfyun.scm.controller.system;

import com.google.code.kaptcha.Producer;
import com.tsfyun.common.base.controller.BaseController;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.common.base.util.TsfPreconditions;
import com.tsfyun.common.base.util.TypeUtils;
import com.tsfyun.scm.security.config.StringRedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/verificationCode")
public class VerificationCodeController extends BaseController {

    @Autowired
    @Qualifier("producer")
    private Producer producer;

    @Autowired
    @Qualifier("producerPlus")
    private Producer producerPlus;

    @Autowired
    private StringRedisUtils stringRedisUtils;

    @PostMapping("captcha")
    public void captcha(HttpServletResponse response)throws IOException {
        String deviceId = request.getParameter("deviceId");
        TsfPreconditions.checkArgument(StringUtils.isNotEmpty(deviceId),new ServiceException("deviceId不能为空"));
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        String type  = TypeUtils.castToString(request.getParameter("type"),"verificationCode");
        BufferedImage image = null;
        //随机选择一种验证码
        int randomInt = new Random().nextInt(2);
        String verifyCode = null;
        if(1 == randomInt) {
            //生成文字加法验证码
            verifyCode = producerPlus.createText();
            String text = verifyCode.substring(0,1) + "+" + verifyCode.substring(1,2) + "=?";
            image = producerPlus.createImage(text);
        } else {
            //生成字母数字验证码
            verifyCode = producer.createText();
            image = producer.createImage(verifyCode);
        }

        //存到redis
        //验证码值
        stringRedisUtils.set("IMG_VERIFY:" + type + "-" + deviceId,verifyCode,5L, TimeUnit.MINUTES);
        //验证码生成方式
        stringRedisUtils.set("IMG_VERIFY_ALGORITHM:"  + type + "-" + deviceId,String.valueOf(randomInt));
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

}
